from get_nornir_obj import get_nornir_obj
from nornir_netmiko.tasks import netmiko_send_command
import re
from datetime import datetime
import os
import logging
import pandas as pd

# logging.basicConfig(filename='test.log', level=logging.DEBUG)
# logger = logging.getLogger('netmiko')

show_arp_cmd_mapping = {
    'cisco_nxos': 'show ip arp',
    'cisco_ios_telnet': 'show ip arp',
    'juniper_junos': 'show arp no-resolve',
    'juniper_junos_telnet': 'show arp no-resolve',
    'generic': 'show arp dynamic',
    'generic_telnet': 'show arp dynamic',
    'huawei_telnet': 'display arp',
    'huawei': 'display arp',
    'hp_comware_telnet': 'display arp',
    'hp_comware': 'display arp',
    'ruijie_os_telnet': 'show ip arp',
    'ruijie_os': 'show ip arp'
}


# def insert_update_arp_table(active_hosts, host):
#     """
#     传入格式化后的IP地址列表，该列表是字典列表，批量插入数据库
#     :param active_hosts: arp表钟的活动IP
#     :param host: 设备
#     :return:
#     """
#     regx = r'([a-f0-9]{4}[\.\-:]?){2}[a-f0-9]{4}|([a-f0-9]{2}[\.\-:]?){5}[a-f0-9]{2}'
#     regx_mac_address = r'([a-f0-9]{2}[:]?){5}[a-f0-9]{2}'
#     active_hosts_list = []
#     host_list = []
#     print('start_date:%s' % datetime.now())
#     # print(active_hosts)
#     for item in active_hosts:
#         mac_address_str = item.get('mac_address')
#         if re.match(regx, mac_address_str, re.IGNORECASE):
#             if re.match(regx_mac_address, mac_address_str, re.IGNORECASE):
#                 mac_address = mac_address_str
#             else:
#                 mac_address_temp = mac_address_str.replace('.', '').replace(':', '').replace('-', '')
#                 mac_address = ':'.join([mac_address_temp[i:i + 2] for i in range(0, len(mac_address_temp), 2)])
#             mac_address = mac_address.upper()
#             access_port = item.get('access_port')
#             ip_address = item.get('ip_address')
#             # 判断是否是10开头的地址
#             if re.match('10.', ip_address):
#                 host_obj = models.Hosts.objects.filter(ip_address=ip_address, service_type_id__in=[2]).first()
#                 if host_obj:
#                     if not (host_obj.mac_address == mac_address and host_obj.status == 1):
#                         host_obj.status = 1
#                         host_obj.mac_address = mac_address
#                         host_list.append(host_obj)
#                     current_date = datetime.now()
#                     current_date_str = current_date.strftime('%Y-%m-%d %H:%M:%S')
#                     host_online_record_obj = models.HostOnlineRecord.objects. \
#                         filter(ip_address=ip_address,
#                                mac_address=mac_address,
#                                scan_time__contains=current_date.strftime('%Y-%m-%d')).last()
#                     if not host_online_record_obj:
#                         temp_obj = models.HostOnlineRecord(
#                             device_id=host.data.get('device_id'),
#                             ip=host_obj,
#                             ip_address=ip_address,
#                             mac_address=mac_address,
#                             online_time=current_date_str,
#                             scan_time=current_date_str,
#                             scan_time_datetime=current_date,
#                             access_switch=host.data.get('name'),
#                             access_port=access_port
#                         )
#                         active_hosts_list.append(temp_obj)
#                         # print('ip_address:%s,insert_date_per:%s' % (ip_address, datetime.now()))
#     print('end_time:%s' % datetime.now())
#     models.HostOnlineRecord.objects.bulk_create(active_hosts_list, batch_size=100)
#     models.Hosts.objects.bulk_update(host_list, ['status', 'mac_address'], batch_size=100)


def get_arp_table_with_netmiko(task_context):
    # devices_obj = models.Devices.objects.filter(ip_address=task_context.host.name).first()
    # inspect_count = devices_obj.inspect_count + 1
    start_time = datetime.now()
    platform = task_context.host.platform
    model = task_context.host.data.get('model')
    vendor = task_context.host.data.get('vendor')
    secret = task_context.host.data.get('secret')
    cmd = show_arp_cmd_mapping.get(platform)
    if platform == 'generic':
        platform = vendor
    templates = 'templates/%s_%s.textfsm' % (platform, '_'.join(cmd.split(' ')))
    if not os.path.exists(templates):
        templates = 'templates/%s_%s_%s.textfsm' % (platform, model, '_'.join(cmd.split(' ')))
    # grant privilige operate
    if vendor == 'transcend':
        cmd = 'show arp'
        templates = 'templates/%s_%s.textfsm' % (vendor, '_'.join(cmd.split(' ')))
        output = task_context.run(netmiko_send_command, command_string='enable', use_timing=True)
        output += task_context.run(netmiko_send_command, command_string='terminal length 0')
    elif vendor == 'ruijie':
        output = task_context.run(netmiko_send_command, command_string='enable', use_timing=True)
        output += task_context.run(netmiko_send_command, command_string=secret, use_timing=True)
        output += task_context.run(netmiko_send_command, command_string='terminal length 0')
    elif vendor == 'huawei':
        if secret:
            output = task_context.run(netmiko_send_command, command_string='super', use_timing=True)
            output += task_context.run(netmiko_send_command, command_string=secret, use_timing=True)
            output += task_context.run(netmiko_send_command, command_string='screen-length 0 temporary')
    elif vendor == 'h3c':
        if secret:
            output = task_context.run(netmiko_send_command, command_string='super', use_timing=True)
            output += task_context.run(netmiko_send_command, command_string=secret, use_timing=True)
            output += task_context.run(netmiko_send_command, command_string='screen-length disable')
    elif vendor == 'juniper':
        pass

    result = task_context.run(netmiko_send_command, command_string=cmd, use_textfsm=True,
                              textfsm_template=templates)
    df1 = pd.DataFrame(result.result)
    df1.to_excel('%s.xlsx' % task_context.host)

    # print('result:%s,result_type:%s,result_result:, result_failed:%s' % (
    #     result, type(result), result.failed))
    # if isinstance(result.result, str):
    #     devices_obj.begin_inspect_time = start_time
    #     devices_obj.end_inspect_time = datetime.now()
    #     devices_obj.insepct_status = 2
    #     devices_obj.exception_cause = '无法解析数据格式'
    #     devices_obj.save()
    # elif isinstance(result.result, list):
    #     insert_update_arp_table(result.result, task_context.host)
    # end_time = datetime.now()
    # if not result.failed:
    #     devices_obj.begin_inspect_time = start_time
    #     devices_obj.end_inspect_time = end_time
    #     devices_obj.insepct_status = 1
    #     devices_obj.inspect_count = inspect_count
    #     devices_obj.exception_cause = ''
    #     devices_obj.save()
    # return result


def collection_arp_table(queryset):
    nr = get_nornir_obj(queryset)
    result = nr.run(task=get_arp_table_with_netmiko)
    for host, multiresult in result.failed_hosts.items():
        if len(multiresult) > 1:
            faild_info = '%s:%s' % (str(multiresult[0].exception).strip(), str(multiresult[1].exception).strip())
        else:
            faild_info = '%s' % str(multiresult[0].exception).strip()
        print(faild_info)
